package dtm

import (
	"context"
	"encoding/json"
	"fmt"
	"gitee.com/xuyiping_admin/pkg/logger/zaplog"
	"gitee.com/xuyiping_admin/pkg/xerr"
	Mqtt "github.com/eclipse/paho.mqtt.golang"
	"go.uber.org/zap"
	"kpt-dtm/model"
	"kpt-dtm/model/yyn"
	"kpt-dtm/service/http"
	"net/url"
	"time"
)

func (s *StoreEntry) YynCommon(ctx context.Context, pastureId int64, path string) (interface{}, error) {
	var (
		res interface{}
		err error
	)
	yConfig, err := s.GetYConfig(pastureId)
	if err != nil {
		return nil, xerr.WithStack(err)
	}
	yMqtt, err := s.GetYMqtt(pastureId)
	if err != nil {
		return nil, xerr.WithStack(err)
	}

	switch path {
	case "token":
		res, err = s.Token(ctx, yConfig)
		if err != nil {
			return nil, xerr.WithStack(err)
		}
	case "house_info":
		res, err = s.SynCowHouseInfo(ctx, yConfig)
		if err != nil {
			return nil, xerr.WithStack(err)
		}
		zaplog.Info("company_list", zap.Any("res", res))
	case "mqtt":
		s.MqttTest(ctx, pastureId)
	case "surplus":
		if err != nil {
			return nil, xerr.WithStack(err)
		}
		err = s.SurplusData(ctx, pastureId, yConfig, yMqtt)
	}
	return res, err
}

func (s *StoreEntry) Token(ctx context.Context, yConfig *model.YConfig) (*yyn.TokenResponse, error) {
	params := url.Values{}
	params.Add("grant_type", "client_credentials")
	params.Add("client_id", "HouseInfo")
	params.Add("client_secret", "secret")

	tokenUrl := fmt.Sprintf("%s%s?%s", yConfig.ApiUrl, yyn.TokenUrl, params.Encode())
	res, err := s.HttpClient.DoPost(tokenUrl, nil, nil)
	if err != nil {
		return nil, err
	}

	zaplog.Info("Token", zap.Any("tokenUrl", tokenUrl), zap.Any("res", string(res)))
	token := &yyn.TokenResponse{}
	if err = json.Unmarshal(res, token); err != nil {
		return nil, err
	}
	return token, nil
}

func (s *StoreEntry) SynCowHouseInfo(ctx context.Context, yConfig *model.YConfig) (*yyn.CowsHouseResponse, error) {
	token, err := s.Token(ctx, yConfig)
	if err != nil {
		return nil, xerr.WithStack(err)
	}

	params := url.Values{}
	params.Add("token", token.AccessToken)
	params.Add("farmNum", yConfig.FarmNumber)
	params.Add("secret", yConfig.Secret)

	houseInfoUrl := fmt.Sprintf("%s%s?%s", yConfig.ApiUrl, yyn.CowHouseListUrl, params.Encode())
	res, err := s.HttpClient.DoPost(houseInfoUrl, nil, []*http.Header{
		&http.Header{
			Key:   "Authorization",
			Value: fmt.Sprintf("Bearer %s", token.AccessToken),
		},
		{
			Key:   "username",
			Value: yConfig.UserName,
		},
	})
	if err != nil {
		return nil, xerr.WithStack(err)
	}

	houseInfo := &yyn.CowsHouseResponse{}
	if err = json.Unmarshal(res, houseInfo); err != nil {
		return nil, xerr.WithStack(err)
	}
	return houseInfo, nil
}

func (s *StoreEntry) MqttTest(ctx context.Context, pastureId int64) {
	s.MqttManager.Subscribe(fmt.Sprintf("%d", pastureId), func(client Mqtt.Client, message Mqtt.Message) {
		go func() {
			body := message.Payload()
			fmt.Println("=====body=====", string(body))
		}()
	})
	time.Sleep(time.Hour)
}
